<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    width="680px"
    :visible="visible"
    :lock-scroll="false"
    :destroy-on-close="true"
    custom-class="ele-dialog-form"
    :title="isUpdate?'修改用户':'添加用户'"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="isEdit?rules:rules2"
      label-width="82px">

      <el-row :gutter="15">
        <el-col :sm="12">

          <el-form-item label="用户账号:" prop="username">
            <el-input
              clearable
              :maxlength="20"
              :disabled="isUpdate"
              v-model="form.username"
              placeholder="请输入用户账号"/>
          </el-form-item>
         <el-form-item
           label="登录密码:"
           prop="password"
           :required="isEdit?true:false"
         >
           <el-input
             show-password
             :maxlength="20"
             v-model="form.password"
             placeholder="请输入登录密码"/>
         </el-form-item>
         <el-form-item label="姓名:" prop="realname">
           <el-input
             clearable
             :maxlength="20"
             v-model="form.realname"
             placeholder="请输入姓名"/>
         </el-form-item>
          <el-form-item label="性别:" prop="gender">
            <el-select
              clearable
              class="ele-block"
              v-model="form.gender"
              placeholder="请选择性别">
              <el-option label="男" :value="1"/>
              <el-option label="女" :value="2"/>
              <el-option label="保密" :value="3"/>
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式:" prop="mobile">
            <el-input
              clearable
              :maxlength="11"
              v-model="form.mobile"
              placeholder="请输入手机号"/>
          </el-form-item>


        </el-col>
        <el-col :sm="12">

          <el-form-item label="学校：" prop="schoolId">
            <el-select
              filterable
              clearable
              v-model="form.schoolId"
              size="small"
              placeholder="-请选择学校-"
              class="ele-block">
              <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="角色:" prop="role_ids">
            <el-select
              multiple
              clearable
              class="ele-block"
              v-model="form.role_ids"
              placeholder="请选择角色">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="院系类型:"  v-if="!(form.role_ids.includes(1) || form.role_ids.includes(5))">
            <!-- <el-select
              clearable
              v-model="form.stype"
              placeholder="请选择院系类型"
              class="ele-fluid">
                            <el-option label="自然院系" value="1"/>
                            <el-option label="体育院系" value="2"/>
                          </el-select> -->
              <el-radio-group
                v-model="form.stype"
                @change="getDepartmentsList">
                        <el-radio :label="1">自然院系</el-radio>
                        <el-radio :label="2">体育院系</el-radio>
                      </el-radio-group>
          </el-form-item>
       <el-form-item prop="departmentsId" label="院系名称:" v-if="!(form.role_ids.includes(1) || form.role_ids.includes(5))">
         <el-select
           filterable
           clearable
           v-model="form.departmentsId"
           @change="getClassList"
           size="small"
           placeholder="-请选择院系-"
           class="ele-block">
           <el-option v-for="item in departmentsList" :key="item.id" :label="item.name" :value="item.id"/>
         </el-select>
       </el-form-item>

          <el-form-item label="状态:" prop="status">
            <el-radio-group
              v-model="form.status">
              <el-radio :label="1">在用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>


        </el-col>
      </el-row>

    </el-form>
    <div slot="footer">
      <el-button
        @click="updateVisible(false)">取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import validate from 'ele-admin/packages/validate';
import uploadImage from '@/components/uploadImage'
import Treeselect from '@riophae/vue-treeselect' // 下拉树
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import regions from 'ele-admin/packages/regions';

export default {
  name: 'UserEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    isEdit:Boolean
  },
  components: {uploadImage, Treeselect},
  data() {
    return {
      // 省市区数据
      regions: regions,
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      // 表单数据
      form: Object.assign({status: 1,role_ids:[]}, this.data),
      // 表单验证规则
      rules: {
         username: [
           {
             required: true,
             type: 'string',
             trigger: 'blur',
             validator: (rule, value, callback) => {
               if (!value) {
                 return callback(new Error('请输入用户账号'));
               }
               this.$http.get('/user/checkUser?username=' + value).then(res => {
                 if (res.data.code !== 0 || !res.data.data.length) {
                  return callback();
                 }
                 if (this.isUpdate && res.data.data[0].username === this.data.username) {
                   return callback();
                 }
                 callback(new Error('账号已经存在'));
               }).catch(() => {
                 callback();
               });
             }
           }
         ],
        realname: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'}
        ],
        schoolId:[
          {required: true, message: '请选择学校', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        birthday: [
          {required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
        level_id: [
          {required: true, message: '请选择职级', trigger: 'blur'}
        ],
        position_id: [
          {required: true, message: '请选择岗位', trigger: 'blur'}
        ],
        dept_id: [
          {required: true, message: '请选择部门', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        // city: [
        //   {required: true, message: '请选择省市区', trigger: 'blur'}
        // ],
        sort: [
          {required: true, message: '请输入排序号', trigger: 'blur'}
        ],
        role_ids: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ],
        email: [
          {pattern: validate.email, message: '邮箱格式不正确', trigger: 'blur'}
        ],
        password: [
           {required: true, pattern: /^[\S]{5,18}$/, message: '密码必须为5-18位非空白字符', trigger: 'blur'}
        ],
        mobile: [
          {required: true,pattern: validate.phone, message: '手机号格式不正确', trigger: 'blur'}
        ]
      },
      // 表单验证规则
      rules2: {
        username: [
          {
            required: true,
            type: 'string',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入用户账号'));
              }
              this.$http.get('/user/checkUser?username=' + value).then(res => {
                if (res.data.code !== 0 || !res.data.data.length) {
                  return callback();
                }
                if (this.isUpdate && res.data.data[0].username === this.data.username) {
                  return callback();
                }
                callback(new Error('账号已经存在'));
              }).catch(() => {
                callback();
              });
            }
          }
        ],
        realname: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'}
        ],
        schoolId:[
          {required: true, message: '请选择学校', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        birthday: [
          {required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
        level_id: [
          {required: true, message: '请选择职级', trigger: 'blur'}
        ],
        position_id: [
          {required: true, message: '请选择岗位', trigger: 'blur'}
        ],
        dept_id: [
          {required: true, message: '请选择部门', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        // city: [
        //   {required: true, message: '请选择省市区', trigger: 'blur'}
        // ],
        sort: [
          {required: true, message: '请输入排序号', trigger: 'blur'}
        ],
        role_ids: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ],
        email: [
          {pattern: validate.email, message: '邮箱格式不正确', trigger: 'blur'}
        ],
        password: [
          {required: false, pattern: /^[\S]{5,18}$/, message: '密码必须为5-18位非空白字符', trigger: 'blur'}
        ],
        mobile: [
          {required: true,pattern: validate.phone, message: '手机号格式不正确', trigger: 'blur'}
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 角色列表
      schoolId:'',
      departmentsId:'',
      roleList: [],
      // 职级列表
      levelList: [],
      // 岗位列表
      positionList: [],
      // 部门列表
      deptList: [],
      schoolList: [],
      departmentsList: [],
    };
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data, {
          role_ids: this.data.roles.map(d => d.id)
        })
        // 取值赋予城市组件
        this.city = this.data.city;
        // 清空密码输入框
        this.form.password = ''
        this.isUpdate = true;
      } else {
        this.form = {};
        this.isUpdate = false;
        // 清空省市区控件
        this.city = [];
      }
    }
  },
  mounted() {
    // 获取学院列表
    this.getSchoolList();
    // 获取院系列表
    this.getDepartmentsList();
    // 获取班级列表
    //this.getClassList();
    // 获取特色班列表
    //this.getFeaturesList();
    this.queryRoles();  // 查询角色列表
    this.getLevelList(); // 查询职级列表
    this.getPositionList(); // 查询岗位列表
    this.getDeptList(); // 查询部门列表
  },
  methods: {
    /**
     * 获取组织列表
     */
    getSchoolList() {
      this.$http.get('/school/getSchoolList').then(res => {
        if (res.data.code === 0) {
          this.schoolList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取院系列表
     */
    getDepartmentsList() {
      //if(this.where.schoolId){
        //this.where.superior = null;
        //this.where.class = null;
        //this.$forceUpdate();
      //}
      this.$http.post('/departments/getDepartmentsList', {sid:this.form.departmentsId,type:this.form.stype}).then(res => {
        if (res.data.code === 0) {
          this.departmentsList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    getClassList(){},
    /* 保存编辑 */
    save() {
	    console.log("==this.form",this.form)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          // 城市数据处理
          this.form = Object.assign({}, this.form, {
            city: this.city
          });
		  debugger
          this.$http.post('/user/edit', this.form).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message({type: 'success', message: res.data.msg});
              if (!this.isUpdate) {
                this.form = {role_ids:[]};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    /* 查询角色列表 */
    queryRoles() {
      this.$http.get('/role/getRoleList').then(res => {
        if (res.data.code === 0) {
          this.roleList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取职级列表
     */
    getLevelList() {
      this.$http.get('/level/getLevelList').then(res => {
        if (res.data.code === 0) {
          this.levelList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取岗位列表
     */
    getPositionList() {
      this.$http.get('/position/getPositionList').then(res => {
        if (res.data.code === 0) {
          this.positionList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取部门列表
     */
    getDeptList() {
      this.$http.get('/dept/getDeptList').then(res => {
        if (res.data.code === 0) {
          this.deptList = this.$util.toTreeData(res.data.data, 'id', 'pid');
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    }
  }
}
</script>

<style scoped>
</style>
